import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// 请求拦截器，添加token到请求头
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理常见错误
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // 清除本地token
      localStorage.removeItem('token');
      
      // 如果有必要，可以在此处重定向到登录页面
      // window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 文章相关API
export const articleService = {
  getArticles: (params) => api.get('/api/articles', { params }),
  getArticleById: (id) => api.get(`/api/articles/${id}`),
  createArticle: (data) => api.post('/api/articles', data),
  updateArticle: (id, data) => api.put(`/api/articles/${id}`, data),
  deleteArticle: (id) => api.delete(`/api/articles/${id}`),
  likeArticle: (id) => api.post(`/api/articles/${id}/like`),
  saveArticle: (id) => api.post(`/api/articles/${id}/save`),
  getUserArticleActions: (id) => api.get(`/api/articles/${id}/user-actions`),
  incrementViewCount: (id) => api.post(`/api/articles/${id}/view`)
};

// 评论相关API
export const commentService = {
  getCommentsByArticleId: (articleId) => api.get(`/api/articles/${articleId}/comments`),
  createComment: (data) => api.post('/api/comments', data),
  updateComment: (id, data) => api.put(`/api/comments/${id}`, data),
  deleteComment: (id) => api.delete(`/api/comments/${id}`),
  likeComment: (id) => api.post(`/api/comments/${id}/like`)
};

// 用户相关API
export const userService = {
  getUserProfile: (username) => api.get(`/api/users/${username}`),
  updateUserProfile: (data) => api.put('/api/users/profile', data),
  getUserArticles: (username) => api.get(`/api/users/${username}/articles`),
  getSavedArticles: () => api.get('/api/users/saved-articles')
};

// 分类和标签API
export const categoryService = {
  getAllCategories: () => api.get('/api/categories'),
  getCategoryById: (id) => api.get(`/api/categories/${id}`),
  getArticlesByCategory: (id, params) => api.get(`/api/categories/${id}/articles`, { params })
};

export const tagService = {
  getAllTags: () => api.get('/api/tags'),
  getTagById: (id) => api.get(`/api/tags/${id}`),
  getArticlesByTag: (id, params) => api.get(`/api/tags/${id}/articles`, { params })
};

// 搜索API
export const searchService = {
  search: (query) => api.get('/api/search', { params: { q: query } })
};

export default api; 